package com.imay.videorecord.view;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.Scroller;


public class AutoAdjustRecylerView extends RecyclerView {
	private final String TAG = "AutoAdjustRecylerView";
	private Scroller mScroller = null;
	private int mLastx = 0;
	//用于设置自动平移时候的速度
	private float mPxPerMillsec = 0;
	private AutoAdjustItemClickListener mListener = null;

	private int mTargetPos;
	private boolean clickable = true;
	
	public AutoAdjustRecylerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		initData(context);
	}

	public AutoAdjustRecylerView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		initData(context);
	}

	public AutoAdjustRecylerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		initData(context);
	}
	
	private void initData(Context context){
		mScroller = new Scroller(context, new Interpolator() {
			public float getInterpolation(float t) {
			      return t;
			  }
		});
	}
	
	public void setScroller(Scroller scroller){
		if(mScroller != scroller){
			mScroller = scroller; 
		}
	}
	
	@Override
	public void computeScroll() {
		// TODO Auto-generated method stub
		super.computeScroll();
		if(mScroller != null){
			if (mScroller.computeScrollOffset())//如果mScroller没有调用startScroll，这里将会返回false。
		    {
		        scrollBy(mLastx - mScroller.getCurrX(), 0);
		        mLastx = mScroller.getCurrX();
		        //继续让系统重绘    
		        postInvalidate();  
		     } 
		}
	}
	
	public AutoAdjustItemClickListener getItemClickListener() {
		return mListener;
	}

	public void setItemClickListener(AutoAdjustItemClickListener listener) {
		this.mListener = listener;
	}
	
	public float getPxPerMillsec() {
		return mPxPerMillsec;
	}

	public void setPxPerMillsec(float pxPerMillsec) {
		this.mPxPerMillsec = pxPerMillsec;
	}
	
	public void checkAutoAdjust(int position){
		int parentWidth = getWidth();//获取父视图的宽度

		//获取可视范围内的选项的头尾位置
		int firstvisiableposition = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
		int count = ((LinearLayoutManager)getLayoutManager()).getItemCount();//获取item总数

		mTargetPos = Math.max(0, Math.min(count - 1, position));//获取目标item的位置（参考listview中的smoothScrollToPosition方法）

		View targetChild = getChildAt(mTargetPos-firstvisiableposition);//获取目标item在当前可见视图item集合中的位置
		if(targetChild == null){
			return;
		}

		int childLeftPx = targetChild.getLeft();//子view相对于父view的左边距
		int childRightPx = targetChild.getRight();//子view相对于父view的右边距
		Log.i(TAG, "target-->left:" + targetChild.getLeft() + "   right:" + targetChild.getRight());


		int childWidth = targetChild.getWidth();
		int centerLeft = parentWidth/2-childWidth/2;//计算子view居中后相对于父view的左边距
		int centerRight = parentWidth/2+childWidth/2;//计算子view居中后相对于父view的右边距
		Log.i(TAG,"rv width:"+parentWidth+"   item width:"+childWidth+"   centerleft:"+centerLeft+"   centerRight:"+centerRight);

		if(childLeftPx>centerLeft){//子view左边距比居中view大（说明子view靠父view的右边，此时需要把子view向左平移
			//平移的起始位置就是子view的左边距，平移的距离就是两者之差
			autoAdjustScroll(childLeftPx,centerLeft);
		}else if(childRightPx<centerRight){
			autoAdjustScroll(childRightPx,centerRight);
		}
	}

	/**
	 * 
	 * @param start 滑动起始位置
	 * @param end 滑动结束位置
	 */
	private void autoAdjustScroll(int start, int end){
		int duration = 0;
        if(mPxPerMillsec != 0){
        	duration = (int)((Math.abs(end - start)/mPxPerMillsec));
        }
		mLastx = start;
		mScroller.startScroll(start, 0, end - start, 0, duration);
		postInvalidate();
	}

	@Override
	public boolean isClickable() {
		return clickable;
	}

	@Override
	public void setClickable(boolean clickable) {
		this.clickable = clickable;
	}

	public abstract class AbstractAutoAdjustViewHolder extends ViewHolder implements View.OnClickListener {
		
		private final static String TAG = "AutoAdjustViewHolder";
		
		public AbstractAutoAdjustViewHolder(View view) {
			super(view);
			view.setOnClickListener(this);
			initView(view);
		}
		
		protected abstract void initView(View view);
		
		/**
		 * 点击监听
		 */
		@Override
		public void onClick(View v) {
			//单击选项的时候判断是否需要移动
			if(clickable){
				checkAutoAdjust(getPosition());
			}
			if(mListener != null){
				mListener.onItemClick(v,getPosition());
			}
		}
	}
}
